import Vue from 'vue'
import VueRouter from 'vue-router'
import $axios from '../util/axios'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const routes = [
    {
        path: '/',
        name: 'navigate',
        component: () => import('../components/Navigate'),
        children: [
            {
                path: 'square',
                name: 'square',
                component: () => import('../components/Square.vue')
            },
            {
                path: 'chat',
                name: 'chat',
                component: () => import('../components/chat.vue'),
                children:[
                    {
                    path: 'friendList',
                    name: 'friendList',
                    component: () => import('../components/friendList.vue')
                    },
                    {
                    path: 'roomlist',
                    name: 'roomList',
                    component: () => import('../components/roomList.vue')
                    }
                ]
            },


        ]
    },
    {
        path: '/roomChat',
        name: 'roomChat',
        component: () => import('../components/roomChat.vue'),
        beforeEnter(to, from, next) {
            var token = JSON.parse(localStorage.getItem(`chatUser`))
            //不能获取this,手动调用$axios
            if (token) {
                next()
            } else {
                next({ name: 'register' })
            }
            if (to.name == 'roomChat') {
                $axios({
                    method: 'post',
                    url: '/api/status',
                    data: {
                        token: token.token
                    }
                }).then(res => {
                    if (res.data.status != 'success') {
                        alert(res.data.message)
                        next({
                            name: 'register'
                        })
                    } else {
                        next()
                    }
                })
            } else {
                next()
            }
        }
    },
    {
        path: '/about',
        name: 'about',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
    },

    {
        path: '/register',
        name: 'register',
        component: () => import('../views/register.vue')
    }
]

const router = new VueRouter({
    routes
})

export default router
